using System;
using System.Collections.Generic;
using DataModel.Reports;

namespace RitaReports.WorkflowResponse
{
    public class WorkflowResponseDataSource : IReportDataSource
    {
        private readonly List<WorkflowResponseReportData> source = new List<WorkflowResponseReportData>();
        private readonly List<WorkflowResponseReportData> units = new List<WorkflowResponseReportData>();

        public List<WorkflowResponseReportData> Units
        {
            get { return units; }
        }

        public WorkflowResponseDataSource(IEnumerable<WorkflowResponseReportData> list)
        {
            source.AddRange(list);
        }

        public void ApplyLocalFilter(IReportFilterConditionds reportFilter)
        {
            WorkflowResponseFilterConditionds filter = (WorkflowResponseFilterConditionds) reportFilter;

            units.Clear();

            if (filter.OrgId != null)
            {
                foreach (WorkflowResponseReportData data in source)
                {
                    if (data.UnitId == filter.OrgId)
                    {
                        units.Add(data);
                        break;
                    }
                }
            }
            else
            {
                units.AddRange(source);
            }

            Comparison<WorkflowResponseReportData> comparison;
            comparison = delegate(WorkflowResponseReportData x, WorkflowResponseReportData y)
                             {
                                 if (filter.SortOrder == ApproveReportSortOrder.FastestToSlowest)
                                 {
                                     return x.AverageTimeSpan.CompareTo(y.AverageTimeSpan);
                                 }

                                 return y.AverageTimeSpan.CompareTo(x.AverageTimeSpan);
                             };

            units.Sort(comparison);

            // in case if no tracks for unit
            if (units.Count == 0 && filter.OrgId != null)
            {
                WorkflowResponseReportData data = new WorkflowResponseReportData();

                data.UnitId = filter.OrgId.Value;
                data.UnitName = filter.OrgName;
                units.Add(data);
            }
        }
    }
}
